import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import { useHistory } from 'react-router-dom'
import logo from '@/assets/logo.png'
import './index.scss'
import { loginAction } from '@/store/actions'
import { useDispatch } from 'react-redux'


type FormData = { mobile: string, code: string, remember: boolean }

const Login = () => {
  // history
  const history = useHistory()
  const dispatch = useDispatch()

  // 检验通过会触发的回调函数
  const onFinish = async (values: FormData) => {
    // console.log('Success:', values);
    const { mobile, code } = values
    // 等异步代码执行完成
    await dispatch(loginAction(mobile, code))
    // 登录成功
    // 提示用户
    message.success('登录成功！')
    // 去首页
    history.push('./home')

  };

  // 校验失败会触发的回调函数
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div className="login">
      {/* 卡片 */}
      <Card className="login-container">
        {/* login */}
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          name='basic'
          labelCol={{ span: 8 }}
          validateTrigger={['onChange', 'onBlur']}
          wrapperCol={{ span: 24 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          initialValues={{
            remember: true,
            mobile: '13911111111',
            code: '246810'
          }}
          autoComplete='off'        >
          <Form.Item
            name='mobile'
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号格式有误' },
            ]}  >
            <Input size="large" />
          </Form.Item>
          <Form.Item
            name='code'
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码格式有误' },
            ]}>
            <Input size="large" />
          </Form.Item>
          <Form.Item name='remember' valuePropName='checked' rules={[
            {
              /*
                参数1:字段名和一些信息
                参数2:字段对应的值 true /false
              */
              validator: (_, value) => {
                // console.log(_)
                // console.log(value)
                return value ? Promise.resolve() : Promise.reject(new Error('请勾选用户协议!'))
              },
            },
          ]} wrapperCol={{ span: 24 }}>
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ span: 24 }}>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login